package day_2022_4_to_7.leetcode;

import java.util.Stack;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}
/**
 * 剑指 Offer 54. 二叉搜索树的第k大节点
 * 与 （KthNode_35_FindMinKNode 给定一棵二叉搜索树，请找出其中的第k小的结点）类似
 * @author haomin
 * @date 2022/05/14 08:28
 **/

public class offer_54_kthLargest{
    public int kthLargest(TreeNode root, int k) {
        if(root == null || k <= 0){
            return 0;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (!stack.isEmpty() || cur != null){
            while (cur != null){
                stack.push(cur);
                cur = cur.right;
            }
            if(!stack.isEmpty()){
                cur = stack.pop();
                k -- ;
                if(k == 0){
                    return cur.val;
                }
            }
            cur = cur.left;
        }
        return 0;
    }
}